﻿using Inovout.Data.Domain;
using Inovout.Data.Service;
using Inovout.Web.Mvc;
using KuaJing.Organization.Domain;
using KuaJing.People.Domain;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace KuaJing.Tasks.WebPages.Controllers
{
    public class EmployeeController : RepositoryController<Employee>
    {
        public override ActionResult Index(QueryCriteria queryCriteria)
        {
            queryCriteria = QueryCriteriaBuilder
                .FilterFor(t => t.Person.Name, FilterOperation.Like)
                .FilterFor(t => t.OfficePhone, FilterOperation.Like)
                .Merge(queryCriteria).QueryCriteria;
            return base.Index(queryCriteria);
        }

        public ActionResult Sync263()
        {
            var organzationElements = TaskController.GetDepartments();
            string companyName = "江苏跨境公司";
            var company = BuildOrganization(
                organzationElements, TaskController.GetEmployees(), organzationElements.Single(e => e.Element("departmentName").Value == companyName)
                );
            company.Employees = null;
            GetService<IRepositoryService<OrganizationUnit>>().Save(company);
            return RedirectToReturnUrl();
        }
        private OrganizationUnit BuildOrganization(IEnumerable<XElement> organizationElements,
            IEnumerable<XElement> employeeElements, XElement organizationElement)
        {
            string name = organizationElement.Element("departmentName").Value;
            var organization = GetService<IRepositoryService<OrganizationUnit>>().Query().SingleOrDefault(o => o.Name == name);
            if (organization == null)
            {
                organization = new OrganizationUnit
                {
                    Name = name,
                    ShortName = name
                };
            }
            foreach (var employeeElement in employeeElements.Where(e => e.Element("departmentid").Value == organizationElement.Element("departmentId").Value))
            {
                AddEmployee(organization, employeeElement);
            }
            foreach (var children in organizationElements.Where(e => e.Element("depId").Value == organizationElement.Element("departmentId").Value))
            {
                organization.Children.Add(BuildOrganization(organizationElements, employeeElements, children));
            }
            return organization;
        }
        private void AddEmployee(OrganizationUnit organization, XElement employeeElement)
        {
            string email = employeeElement.Element("userid").Value;
            var employee = GetService<IRepositoryService<Employee>>().Query()
                .SingleOrDefault(e => e.Person.Contacts.Any(c => c.Value == email && c.Way == ContactWay.EMail));
            if (employee == null)
            {
                employee = new Employee
                {
                    Person = new Person(employeeElement.Element("name").Value,
                        new Contact { Way = ContactWay.EMail, Value = email }),
                     Status= EmployeeStatus.OnJob
                };
                organization.Employees.Add(employee);
            }
        }
        #region Organization
        //private void SyncOrganization(string rooId)
        //{
        //     OrganizationUnit organizationUnit = GetRootOrganization(rooId);
        //    GetService<IRepositoryService<OrganizationUnit>>()                .Save(organizationUnit);
        //}
        //private OrganizationUnit GetRootOrganization(string rootId)
        //{
        //    XmapiImplService xmail263Service = TaskController.x263Service;
        //    string sign = TaskController.Md5SignArg("huay@samples.cn");
        //    string xml = xmail263Service.getDepartment(userid, domain, account, sign);
        //    IEnumerable<XElement> organizationElements = XDocument.Parse(xml).Descendants("department");
        //    var rootOrganization = BuildOrganization(organizationElements.Single(e => e.Element("departmentId").Value == rootId));
        //    BuildChildOrganizations(rootOrganization, rootId, organizationElements);
        //    return rootOrganization;
        //}
        //private OrganizationUnit BuildOrganization(XElement element, string parentPath = null)
        //{
        //    string name = element.Element("departmentName").Value;
        //    string namePath = parentPath == null ? name : parentPath + "/" + name;
        //    return organizationUnitService.Query().SingleOrDefault(org => org.NamePath == namePath) ??
        //     new OrganizationUnit(name, namePath) { DepartmentId = element.Element("departmentId").Value };
        //}
        //private void BuildChildOrganizations(OrganizationUnit parent, string parentId, IEnumerable<XElement> organizationElements)
        //{
        //    foreach (var element in organizationElements.Where(e => e.Element("depId").Value == parentId))
        //    {
        //        OrganizationUnit child = BuildOrganization(element, parent.NamePath);
        //        child.Parent = parent;
        //        parent.Children.Add(child);
        //        BuildChildOrganizations(child, element.Value, organizationElements);
        //    }
        //}
        //#endregion

        //#region Employee
        //private void SyncEmployee()
        //{
        //    XmapiImplService service = new XmapiImplService();
        //    string sign = Md5Sign(domain + account + key);
        //    string xml = service.getDomainUserlist_New(domain, account, sign);
        //    var userElements = XDocument.Parse(xml).Descendants("user");
        //    foreach (var organization in organizationUnitService.Query().ToArray())
        //    {
        //        //Q Org.Position通过迭代Employee。Position来提取。在Orgazization中实现，不在这里实现。
        //        BuildEmployees(organization, userElements);
        //        organizationUnitService.Save(organization);
        //    }
        //}
        //private void BuildEmployees(OrganizationUnit organization, IEnumerable<XElement> userElements)
        //{
        //      foreach (XElement element in userElements.Where(u => u.Element("departmentid").Value == organization.DepartmentId))
        //    {
        //        var employee = BuildEmployee(element);
        //        if (!organization.Employees.Contains(employee))
        //        {
        //            organization.addEmployee(employee);
        //        }
        //    }
        //}
        //private Employee BuildEmployee(XElement element)
        //{
        //    string mail = element.Element("userid").Value;
        //    string name = element.Element("name").Value;
        //    string mobile = element.Element("mobile") == null ? null : element.Element("mobile").Value;
        //    string position = element.Element("office").Value;
        //    Contact mobileContact = string.IsNullOrEmpty(mobile) ? null :
        //        contactService.Query().SingleOrDefault(c => c.Label == ContactMethod.Mobile && c.Value == mobile) ?? new Contact(ContactMethod.Mobile, mobile);
        //    Contact mailContact = contactService.Query().SingleOrDefault(c => c.Label == ContactMethod.EMail && c.Value == mail) ?? new Contact(ContactMethod.EMail, mail);
        //    if (mailContact.Person != null && mailContact.Person == mobileContact.Person)
        //    {
        //        return employeeService.Query().Single(e => e.Person == mailContact.Person);
        //    }
        //    else
        //    {
        //        return new Employee(BuildPerson(name, mobileContact, mailContact), BuildPosition(position));
        //    }
        //}

        //private Person BuildPerson(string name, Contact mobileContact, Contact mailContact)
        //{
        //    Person person = new Person(name, mobileContact, mailContact);
        //     return person;
        //}

        //private Position BuildPosition(string position)
        //{
        //    return positionService.Query().SingleOrDefault(p => p.Name == position) ?? new Position(position);
        //}
        #endregion


    }
}